package com.mydemo.admin.service.impl;

import com.mydemo.admin.mapper.SysRoleMapper;
import com.mydemo.admin.service.ISysRoleService;
import com.mydemo.common.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Last_Island
 * @version 1.0
 */
@Service
public class SysRoleServiceImpl implements ISysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 根据角色id获取角色信息
     *
     * @param roleId 角色id
     * @return
     */
    @Override
    public List<Role> getRoleByRoleId(Long roleId) {
        Role role = sysRoleMapper.getRoleByRoleId(roleId);
        role.setPermissions(sysRoleMapper.getRolePermissionByRoleId(roleId));
        List<Role> roles = new ArrayList<>();
        roles.add(role);
        return roles;
    }

    /**
     * 获取所有角色信息
     * @return 角色信息列表
     */
    @Override
    public List<Role> getRoleList(Role role){
        return sysRoleMapper.getRoleList(role);
    }

    /**
     * 添加角色
     *
     * @param role 角色信息
     * @return
     */
    @Transactional
    @Override
    public boolean addRole(Role role) {
        if (sysRoleMapper.roleKeyCount(role.getRoleKey()) > 0)
            throw new RuntimeException("角色已存在,请更换角色字符");
        int i = sysRoleMapper.addRole(role),j = 1;
        if (!role.getPermissions().isEmpty())
            j = sysRoleMapper.addRolePermission(role);
        if (!(i > 0 && j > 0)) {
            throw new RuntimeException("添加角色失败");
        }
        return true;
    }

    /**
     * 删除角色
     *
     * @param roleId
     * @return
     */
    @Transactional
    @Override
    public boolean deleteRole(Long roleId) {
        isAdmin(roleId);
        sysRoleMapper.deleteRolePermission(roleId);
        if (sysRoleMapper.deleteRole(roleId) <= 0)
            throw new RuntimeException("删除角色失败");
        return true;
    }

    /**
     * 更新角色
     *
     * @param role
     * @return
     */
    @Transactional
    @Override
    public boolean updateRole(Role role) {
        isAdmin(role.getRoleId());
        Role roleByRoleId = sysRoleMapper.getRoleByRoleId(role.getRoleId());
        sysRoleMapper.deleteRolePermission(role.getRoleId());
        if (!role.getRoleKey().equals(roleByRoleId.getRoleKey()) && sysRoleMapper.roleKeyCount(role.getRoleKey()) > 0)
            throw new RuntimeException("角色已存在,请更换角色字符");
        int i = sysRoleMapper.updateRole(role),j = 1;
        if (!role.getPermissions().isEmpty())
            j = sysRoleMapper.addRolePermission(role);
        if (!(i > 0 && j > 0)) {
            throw new RuntimeException("更新角色失败");
        }
        return true;
    }

    /**
     * 判断是否为超级管理员角色
     * @param roleId
     */
    private void isAdmin(Long roleId){
        if (roleId == 1L)
            throw new RuntimeException("无法对超级管理员角色进行操作！！！");
    }
}
